package com.speily.lock.service.impl;

import com.speily.lock.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 *
 * @author SPL
 * @since 2020/01/02 15:22
 */
@Service
public class TestServiceImpl implements TestService {


    @Autowired
    private RedissonClient redissonClient;


    @Override
    public void test() {
        RLock lock = redissonClient.getLock("this thread");
        long threadId = Thread.currentThread().getId();
        boolean locked = false;
        try{
            locked = lock.tryLock(10, TimeUnit.SECONDS);
            if (locked){
                //开始写业务
                System.out.println(threadId + "锁住了。。。");
                System.out.println(threadId + "模拟业务耗时开始。。");
                Thread.sleep(10);
                System.out.println(threadId + "模拟业务耗时结束。。。");
            } else {
                System.out.println(threadId + "没锁住。。。");
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            if (locked){
                System.out.println(threadId + "释放锁");
                System.out.println();
                lock.unlock();
            }
        }
    }
}
